package com.tyqx.biz.controller.config;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ListSortDate {

    /**
     * 按照JSONArray中的对象的某个字段进行排序(采用fastJson)
     * @param jsonArr json数组字符串
     */
    public static JSONArray jsonArraySort(JSONArray jsonArr) {
        JSONArray sortedJsonArray = new JSONArray();
        List<JSONObject> jsonValues = new ArrayList<JSONObject>();
        for (int i = 0; i < jsonArr.size(); i++) {
            jsonValues.add(jsonArr.getJSONObject(i));
        }
        Collections.sort(jsonValues, new Comparator<JSONObject>() {
            private static final String KEY_NAME = "accidentDate";
            String string1;
            String string2;
            @Override
            public int compare(JSONObject a, JSONObject b) {
                try {
                    string1= a.getString(KEY_NAME).replaceAll("-", "");
                    string2= b.getString(KEY_NAME).replaceAll("-", "");
                } catch (JSONException e) {
                    // 处理异常
                }
                //这里是按照时间逆序排列,不加负号为正序排列
                return -string1.compareTo(string2);
            }
        });
        for (int i = 0; i < jsonArr.size(); i++) {
            sortedJsonArray.add(jsonValues.get(i));
        }
        return sortedJsonArray;
    }

    public static void main(String[] args) {
//        String jsonArrStr = "[ { \"accidentDate\": \"2016-05-25\", \"Name\": \"zhangChan\" },{ \"accidentDate\": \"2016-05-23\", \"Name\": \"alanLuke\" },{ \"accidentDate\": \"2016-05-26\", \"Name\": \"sansiny\" }]";
//        String jsonArraySort = jsonArraySort(jsonArrStr);
//        System.out.println("逆序后："+jsonArraySort);
    }


}
